/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lijigou.shopping;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.concurrent.ExecutorService;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.Util;

 
import com.connect.BaseActivity;
import com.connect.Constant;
import com.connect.Kaixin;
import com.connect.PostRecordTask;

public class OAuthKaixinActivity extends BaseActivity {

	// ��ǰҳ����ܵ�״̬��
	private static final int STATE_INITIAL = 0;
	private static final int STATE_UPLOADING = 1;
	private static final int STATE_FINSHED = 2;
	private Drawable drawableCache=null;
	private EditText mEontentEdit;
	private String content;
	private int activityState = STATE_INITIAL;
	private PostRecordTask getDataTask;
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	 public Handler waitHander = new Handler(){   
	    	public void handleMessage(Message msg) {  
	    		if(msg.what==0){
	    			if(drawableCache!=null){
	    			 
	    		    			BitmapDrawable bd = (BitmapDrawable) drawableCache;
	    	    				Bitmap bm = bd.getBitmap();
	    	    				ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    	                     //得到输出流
	    	    				bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
	    	                     //转输入流
	    	    				InputStream isBm = new ByteArrayInputStream(baos .toByteArray());
	    						getDataTask = new PostRecordTask();
	    						getDataTask.execute(kaixin, handler, content, isBm,
	    								OAuthKaixinActivity.this);
	    					};

	    		}   
	    	}
	    };   
	/** Called when the activity is first created. */
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.postrecord_activity);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.share_mblog_view);
		 
		String accessToken = null;
		String refreshToken= null;
		String expiresIn= null;
//		expiresIn.
		
		
		   Intent intent=this.getIntent();
		 
		   if(!intent.hasExtra("login")){
			   Uri uri = this.getIntent().getData();
			   String[] tem=uri.toString().split("&");
			   for(int i=0;i<tem.length;i++){
				   if(i==0){
					   accessToken=tem[i].split("=")[1];
				   }else if(i==1){
					   expiresIn=tem[i].split("=")[1];
				   }else if(i==2){
					   
				   }else if(i==3){
					   refreshToken=tem[i].split("=")[1];
				   }
			   }
				Long temp=Long.parseLong(expiresIn);
				SharedPreferences sp = OAuthKaixinActivity.this.getSharedPreferences(Kaixin.KAIXIN_SDK_STORAGE,
						Context.MODE_PRIVATE);
				sp.edit().putString(Kaixin.KAIXIN_SDK_STORAGE_ACCESS_TOKEN, accessToken).commit();
				sp.edit().putString(Kaixin.KAIXIN_SDK_STORAGE_REFRESH_TOKEN, refreshToken).commit();
				sp.edit().putLong(Kaixin.KAIXIN_SDK_STORAGE_EXPIRES, temp).commit();
				if (accessToken != null && refreshToken != null
						&& expiresIn != null) {
					try {
						Kaixin.setAccessToken(accessToken);
						Kaixin.setRefreshToken(refreshToken);
						Kaixin.setAccessExpiresIn(expiresIn);
						
						}catch (Exception e) {
							// TODO: handle exception
						}
				}
		
	 
		   }
		
		   TextView  back = (TextView) this.findViewById(R.id.title_btn_left);
			back.setBackgroundResource(R.drawable.title_back_normal);
//			back.setBackgroundResource(R.drawable.title_btn);c
			
	 
			this.findViewById(R.id.titleLeftView).setOnClickListener(new OnClickListener() {
				
				
				public void onClick(View v) {
					MSystem.pv+=1;
					// TODO Auto-generated method stub
					OAuthKaixinActivity.this.finish();
				}
			});   
		   
		   
		   
		
		TextView postBtn = (TextView) findViewById(R.id.title_btn_right);
		
		postBtn.setText("分享到开心网");
		mEontentEdit = (EditText) findViewById(R.id.etEdit);
		
		mEontentEdit.setText("我刚用@手机买团购出手了 现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou");
		this.findViewById(R.id.titleRightView).setOnClickListener(new OnClickListener() {

			
			public void onClick(View arg0) {
				MSystem.pv+=1;
				content = String.valueOf(mEontentEdit.getText()).trim();
				if (content.length() == 0) {
					Toast.makeText(getApplicationContext(),
							"请输入内容", Toast.LENGTH_LONG).show();
					return;
				}
				activityState = STATE_UPLOADING;
				showDialog(Constant.DIALOG_ID_UPLOADING);
				getImgae(ShopDetailActivity.shareShopid,ShopDetailActivity.shareShopImage);
				
				
			}
		});
	}

	
	
	private void getImgae(final String shareShopid,final String imageUrl) {
		// TODO Auto-generated method stub
		String filePath = "/sdcard/tuangou/"+shareShopid+"large.jpg";
		
		File file=new File(filePath);
		if(file.exists()){
			try{
				Drawable drawable=Drawable.createFromPath(filePath);
				if(drawable!=null){
					waitHander.sendEmptyMessage(0);
					drawableCache=drawable;
				}else{
					file.delete();
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			executorService.execute(new Thread() {
				
				public void run() {
					InputStream is = null;
					Drawable drawable = null;
					if (getNetConnectState(OAuthKaixinActivity.this)) {
						try {
							Drawable sirectDrawable = null;
							HttpURLConnection conn = Util.getHttpURLConnection(imageUrl);
							conn.setDoInput(true);
							if (conn.getResponseCode() == 200) {
								is = conn.getInputStream();
								int size = conn.getContentLength();
								if (is != null) {
									Bitmap bitmap = BitmapFactory.decodeStream(is);
									drawable = new BitmapDrawable(bitmap);
									sirectDrawable = drawable;
									if (sirectDrawable != null && size > 4) {
										drawableCache = drawable;
										waitHander.sendEmptyMessage(0);
										try {
											String filePath = "/sdcard/tuangou/" + shareShopid + "large.jpg";
											saveBitMap(bitmap, filePath);
										} catch (Exception e) {
											e.printStackTrace();
										}
									}

								}
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}
			});
		}
			// TODO: handle exception
		}
	
 	public static boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
	public static void saveBitMap(Bitmap bitmap, String filePath)
    throws IOException, FileNotFoundException {
	
		File fp = new File("/sdcard/tuangou");
		File file = new File("/sdcard/tuangou/.nomedia");
		if (!fp.exists()) {
			fp.mkdir();
			if((!file.exists())){  
				file.createNewFile();
			}
		}else{
			File f = new File(filePath);
			f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
		}
}
	
	
	public void doOnResume() {
		if (activityState == STATE_INITIAL) {
			activityState = STATE_UPLOADING;
			stateInitOnCreate();
		} else if (activityState == STATE_UPLOADING) {
			stateInitOnCreate();
		} else if (activityState == STATE_FINSHED) {
			setStateOnFetchFinished();
		}
	}

	
	protected void doOnPause() {
		try{
			if (activityState == STATE_UPLOADING) {
				dismissDialog(Constant.DIALOG_ID_UPLOADING);
				getDataTask.cancel(true);
			} else if (activityState == STATE_FINSHED) {
				// do nothing
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	protected void dealWithMessage(Message msg) {
		dismissDialog(Constant.DIALOG_ID_UPLOADING);

		if (msg.what == Constant.RESULT_POST_RECORD_OK) {
			if (activityState == STATE_UPLOADING) {
				activityState = STATE_FINSHED;

				Toast.makeText(getApplicationContext(),
						"分享成功了哦...", Toast.LENGTH_LONG).show();
				OAuthKaixinActivity.this.finish();
			}
		} else if (msg.what == Constant.RESULT_POST_RECORD_FAILED) {
			if (activityState == STATE_UPLOADING) {
				activityState = STATE_FINSHED;
				Toast.makeText(getApplicationContext(),
						"分享失败了..", Toast.LENGTH_LONG).show();
			}
		} else {
			super.dealWithMessage(msg);
		}
	}
	
	
	

protected Dialog onCreateDialog(int id) {
	if (id == Constant.DIALOG_ID_UPLOADING) {
		return ProgressDialog.show(this, "", "请稍候,正在分享中...",
				true, true, null);
	} else {
		return super.onCreateDialog(id);
	}
}

	protected void stateInitOnCreate() {
	}

	protected void setStateOnFetchFinished() {

	}
}